package kr.slm.updatetool.paser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import kr.slm.updatetool.io.IOUtil;

import org.eclipse.swt.widgets.ProgressBar;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathTest {

	public static void start(ProgressBar bar, String lastest_path, String now_path) throws Exception {

		XPath xpath = XPathFactory.newInstance().newXPath();

		List<Map<String, Object>> updateList = updateStart(XmlLoad.getXmlDoc(lastest_path), xpath, now_path);

		versionDownload(updateList, bar, lastest_path, now_path);
	}

	/**
	 *  업데이트할 list작성
	 * Date    2014. 9. 25. 
	 * @작성자   HY
	 * @param doc
	 * @param xpath
	 * @param now_path
	 * @return
	 */
	public static List<Map<String, Object>> updateStart(Document doc, XPath xpath, String now_path) {

		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

		NodeList lastest_nodelist = null;//최신 버전을 가지고잇는 노드리스트
		try {
			XPathExpression expr = xpath.compile("/repository/artifacts/artifact[@classifier='osgi.bundle']");

			lastest_nodelist = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);//selector로 artifact를 노드리스트로 가져오기

			for (int i = 0; i < lastest_nodelist.getLength(); i++) {

				String id = lastest_nodelist.item(i).getAttributes().getNamedItem("id").getNodeValue();//플러그인 id가져오기
				String lastest_version = lastest_nodelist.item(i).getAttributes().getNamedItem("version").getNodeValue();//버전정보가져오기

				if (lastest_version != null) {//플러그인이 있는상태 최신이던 예전꺼든
					if (!checkVersion(id, lastest_version, xpath, now_path)) {// 최신이 아니면 list에 추가
						result.add(createMap(id, lastest_version));
					}
				} else {//없는상태 가능한지는 나중에 확인
				}

			}

		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(result);
		return result;

	}

	
	/**
	 * 
	 * Date    2014. 9. 25. 
	 * @작성자   HY
	 * @param id 최신버전 id
	 * @param lastest_version 최신버전
	 * @param xpath
	 * @param now_path
	 * @return
	 * @throws XPathExpressionException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	private static Boolean checkVersion(String id, String lastest_version, XPath xpath, String now_path) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {

		Node now_node;
		String now_version;// 현재버전

		XPathExpression expr = xpath.compile("/repository/artifacts/artifact[@id=" + "'" + id + "'" + "]");

		now_node = (Node) expr.evaluate(XmlLoad.getXmlDoc(now_path), XPathConstants.NODE);// 노드로 추출

		if (now_node != null) {// 플러그인이 있을때
			now_version = now_node.getAttributes().getNamedItem("version").getNodeValue();// 버전가져오기

			if (!versionToString(now_version).equals(versionToString(lastest_version))) {// 최신버전이아닐때

				return false;
			}

		} else {// 플러그인이 업을때
				// 다운로드
			return false;
		}
		return true; // 최신버전일때
	}

	private static Map<String, Object> createMap(String id, String version) {

		Map<String, Object> result = new HashMap<String, Object>();

		result.put("id", id);
		result.put("version", version);

		return result;
	}

	
	/**
	 * ex)1.4.1.v20130515-1857->1.4.1
	 * 버전 뒷 부분을 자르기
	 * Date    2014. 9. 25. 
	 * @작성자   HY
	 * @param version
	 * @return
	 */
	private static String versionToString(String version) {

		return version.substring(0, version.lastIndexOf("."));
	}

	
	/**
	 * 아직 다운로드할때가 없으니 폴더간에 복사로 대신해서 만듬
	 * 바뀔때 총 3가지가 바뀌어야함 플러그인,config.ini,artifact.xml
	 * 
	 * Date    2014. 9. 25. 
	 * @작성자   HY
	 * @param downList 다운로드 목록
	 * @param bar 프로그래스바
	 * @param lastest_path 최신버전
	 * @param now_path 현재버전
	 */
	private static void versionDownload(List<Map<String, Object>> downList, ProgressBar bar, String lastest_path, String now_path) {

		for (int i = 0; i < downList.size(); i++) {

			String now_file_path = now_path + "/eclipse/plugins/" + downList.get(i).get("id") + "_" + downList.get(i).get("version") + ".jar";
			String lastest_file_path = lastest_path + "/eclipse/plugins/" + downList.get(i).get("id") + "_" + downList.get(i).get("version") + ".jar";
			IOUtil.fileCopy(lastest_file_path, now_file_path);
			int persent = (int) ((double) i + 1 / (double) downList.size() * 100.0);
			bar.setSelection(persent);
		}
		//config.ini파일교채
		String now_config_path = now_path + "/eclipse/configuration/config.ini";
		String last_config_path = lastest_path + "/eclipse/configuration/config.ini";

		IOUtil.fileCopy(last_config_path, now_config_path);//config.ini 파일 변경

		//artifacts.xml파일교채
		String now_artifacts_path = now_path + "/eclipse/artifacts.xml";
		String last_artifacts_path = lastest_path + "/eclipse/artifacts.xml";

		//테스트를위해 막아둠 나중엔 풀어야함!
		IOUtil.fileCopy(last_artifacts_path, now_artifacts_path);//artifacts.xml 파일 변경 

	}
}